import 'package:flutter/material.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/pages/order_settlement/widgets/CachedImage.dart';
import 'package:yp/pages/order_settlement/widgets/EsIconButton.dart';
import 'package:yp/pages/order_settlement/widgets/style.dart';
import 'package:get/get.dart';
import 'package:yp/config/config.dart';
import 'package:yp/router.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yp/pages/order_create/widgets/shop_widgets.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/helper.dart';
import 'logic.dart';
import 'state.dart';

class OrderCreatePage extends StatefulWidget {
  OrderCreatePage({Key key}) : super(key: key);

  @override
  _OrderCreatePageState createState() {
    return _OrderCreatePageState();
  }
}

class _OrderCreatePageState extends State<OrderCreatePage> {
  final OrderCreateLogic logic = Get.put(OrderCreateLogic());
  final OrderCreateState state = Get.find<OrderCreateLogic>().state;

  @override
  void initState() {
    print('22222222222222222222222222222222');
    setState(() {
      state.edit = false;
    });

    if (SpUtil.getInt('empeNumId') != '') {
      logic.onReady();
    }
    // TODO: implement initState
    super.initState();
  }

  /// 失效商品部分
  Widget _expireGoodsList() {
    return Visibility(
      visible: state.sxGoodList?.isNotEmpty ?? false,
      child: Column(children: [
        // ShopName('失效商品', showIcon: false),
        YpLine(),
        ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) => _expireGoods(index),
            separatorBuilder: (context, index) => YpLine(indent: 48),
            itemCount: state.sxGoodList?.length),
        YpLine(indent: 48),
        OutlinedButton(
            onPressed: () {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: Text('提示'),
                      content: Text('是否删除失效商品'),
                      actions: <Widget>[
                        FlatButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: Text('取消'),
                        ),
                        FlatButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                            logic.clearsxArr();
                          },
                          textColor: Colors.red,
                          child: Text('确定'),
                        ),
                      ],
                    );
                  });
            },
            style: OutlinedButton.styleFrom(
              backgroundColor: EsColors.White,
              padding: EdgeInsets.zero,
              minimumSize: Size(88, 24),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12)),
              side: BorderSide(color: EsColors.BackGround, width: 1),
            ),
            child: Text(
              '清空失效商品',
              style: TextStyle(
                  color: EsColors.Content,
                  fontSize: EsSizes.XS,
                  fontWeight: EsFontWeights.Normal),
            )),
        SizedBox(height: 15),
      ]),
    );
  }

  /// 失效商品item
  Widget _expireGoods(int index) {
    return Stack(children: [
      Padding(
        padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
                padding: const EdgeInsets.fromLTRB(4, 1, 4, 2),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: EsColors.TitleSecondary,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  '下架',
                  style: TextStyle(
                      color: EsColors.White,
                      fontSize: EsSizes.XXS,
                      fontWeight: EsFontWeights.Normal),
                )),
            SizedBox(width: 8),
            CachedImage(
                width: 80,
                height: 80,
                margin: EdgeInsets.fromLTRB(0, 10, 8, 12),
                scale: BoxFit.cover,
                path: state.sxGoodList[index]['image_default_id']),
            SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    state.sxGoodList[index]['title'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.MD,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  Text(
                    state.sxGoodList[index]['title'] == null
                        ? ''
                        : state.sxGoodList[index]['title'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.SM,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 18),
                    child: RichText(
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      text: TextSpan(
                          text: '￥',
                          style: TextStyle(
                              fontSize: EsSizes.XXS,
                              color: EsColors.TitleSecondary,
                              fontWeight: EsFontWeights.Normal),
                          children: <TextSpan>[
                            TextSpan(
                                text:
                                    state.sxGoodList[index]['price'].toString(),
                                style: TextStyle(
                                    fontSize: EsSizes.LG,
                                    color: EsColors.TitleSecondary,
                                    fontWeight: EsFontWeights.Medium)),
                          ]),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
      Positioned(
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          child: DecoratedBox(
            decoration: BoxDecoration(color: EsColors.White.withOpacity(0.8)),
          ))
    ]);
  }

  Widget GWC() {
    return Visibility(
      child: ListView(
        children: [
          Container(
              child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Center(
                child: Image(
                  image: AssetImage("assets/images/gwcem.png"),
                ),
              ),
              Center(
                child: GestureDetector(
                  onTap: () {
                    // final MainAppLogic MainApplogic = Get.put(MainAppLogic());
                    final MainLogic mainLogic = Get.put(MainLogic());
                    mainLogic.switchTap(0);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 15, top: 15),
                    padding:
                        EdgeInsets.only(left: 12, right: 12, top: 5, bottom: 5),
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.red, width: 1),
                        //边框
                        borderRadius: BorderRadius.all(
                          //圆角
                          Radius.circular(20.0),
                        )),
                    child: Text(
                      '去购物',
                      style: TextStyle(
                        color: Colors.red,
                      ),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible: state.TJlist.length > 0,
                child: Column(
                  children: [_guessLickTitle(), _guessLick()],
                ),
              )
            ],
          )),
        ],
      ),
      visible: state.cartDataList.length <= 0,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          backgroundColor: Config.mainColor,
          brightness: Brightness.light,
          iconTheme: IconThemeData(color: Colors.white),
          actions: [
            GetBuilder<OrderCreateLogic>(builder: (logic) {
              if (state.cartDataList.length > 0) {
                return TextButton(
                  onPressed: () {},
                  child: TextButton(
                    onPressed: () {
                      setState(() {
                        logic.setDel();
                        //     Get.toNamed(RouteConfig.orderComplete);
                      });
                    },
                    child: Text(
                      state.edit ? '完成' : '编辑',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                );
              } else {
                return Container();
              }
            })
          ],
          title: Text(
            "购物车",
            style: TextStyle(color: Colors.white, fontSize: 32.sp),
          ),
          centerTitle: true,
          elevation: 0,
        ),
        body: GetBuilder<OrderCreateLogic>(builder: (logic) {
          return state.cartDataList.length <= 0
              ? GWC()
              : Column(
                  children: [
                    Expanded(
                      child:
                          ListView(shrinkWrap: true, primary: true, children: [
                        Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                          ),
                          padding: EdgeInsets.only(
                              left: 30.w, top: 20.w, bottom: 20.w),
                          child: Column(
                            children: [],
                          ),
                        ),

                        //商品部分
                        Container(
                          color: Colors.white,
                          padding: EdgeInsets.only(bottom: 28.w),
                          child: Column(
                            children: [
                              logic.state.cartDataList != null
                                  ? ListView.builder(
                                      itemBuilder: (ctx, index) {
                                        return ShopWidget(
                                            shopIndex: index, logic: logic);
                                      },
                                      shrinkWrap: true,
                                      physics: NeverScrollableScrollPhysics(),
                                      itemCount:
                                          logic.state.cartDataList.length,
                                    )
                                  : Container(
                                      height: 20.w,
                                    ),
                              Visibility(
                                  visible: state.cartDataList.length > 0,
                                  child: _expireGoodsList()),
                            ],
                          ),
                        ),
                        Visibility(
                          visible: state.TJlist.length > 0,
                          child: Column(
                            children: [_guessLickTitle(), _guessLick()],
                          ),
                        )

                        // if(SpUtil.getInt('accountType') == 1)
                      ]),
                    ),
                    // _expireGoodsList(),
                    Visibility(
                      visible: state.cartDataList.length > 0,
                      child: Container(
                        color: Colors.white,
                        width: 750.w,
                        height: 100.w,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 410.w,
                              padding: EdgeInsets.symmetric(horizontal: 15.w),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      var params = {
                                        "usr_num_id":
                                            SpUtil.getInt('empeNumId'),
                                        // "emp_num_id": SpUtil.getInt('empeNumId'),
                                        "use_platform": 1,
                                        "type":
                                            state.cartData["checkedall"] == 0
                                                ? 'cancel'
                                                : "checked",
                                        "inv_from_type":
                                            state.sendType == 1 ? 3 : 2,
                                        'access_token':
                                            SpUtil.getString('token'),
                                      };
                                      print('购物车全选');
                                      logic.cartChoose(params);
                                    },
                                    child: RichText(
                                      text: TextSpan(
                                        children: [
                                          WidgetSpan(
                                            child: Image.asset(
                                              state.cartData["checkedall"] == 0
                                                  ? "assets/images/selectIcon1.png"
                                                  : "assets/images/select1.png",
                                              width: 50.w,
                                            ),
                                          ),
                                          WidgetSpan(
                                            child: SizedBox(
                                              width: 15.w,
                                            ),
                                          ),
                                          TextSpan(
                                            text: '全选',
                                            style: TextStyle(
                                                color: Color(0xff666666),
                                                fontSize: 28.sp),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  RichText(
                                    text: TextSpan(
                                      children: [
                                        TextSpan(
                                          text: state.edit ? '' : '共',
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 30.sp),
                                        ),
                                        TextSpan(
                                          text: state.edit ? '' : '￥',
                                          style: TextStyle(
                                              color: Config.mainColor,
                                              fontSize: 28.sp),
                                        ),
                                        TextSpan(
                                          text: state.edit
                                              ? ''
                                              : state.cartData.isEmpty
                                                  ? "0.00"
                                                  : state
                                                      .cartData["total_price"]
                                                      .toString(),
                                          style: TextStyle(
                                              color: Config.mainColor,
                                              fontSize: 30.sp),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                if (!state.edit) {
                                  logic.GoSettlement();
                                } else {
                                  showDialog(
                                      context: context,
                                      barrierDismissible: false,
                                      builder: (BuildContext context) {
                                        return AlertDialog(
                                          title: Text('提示'),
                                          content: Text('是否删除商品'),
                                          actions: <Widget>[
                                            FlatButton(
                                              onPressed: () =>
                                                  Navigator.of(context).pop(),
                                              child: Text('取消'),
                                            ),
                                            FlatButton(
                                              onPressed: () {
                                                Navigator.of(context).pop();
                                                logic.allDed();
                                              },
                                              textColor: Colors.red,
                                              child: Text('确定'),
                                            ),
                                          ],
                                        );
                                      });
                                }
                              },
                              child: Container(
                                color: Config.mainColor,
                                height: 100.w,
                                width: 340.w,
                                child: Center(
                                  child: Text(
                                    state.edit
                                        ? '删除'
                                        : '去结算(${state.clickNum})',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 36.sp,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
        }));
  }

  /// 猜你喜欢
  Widget _guessLickTitle() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: Row(
        children: [
          Expanded(child: YpLine()),
          Container(
            width: 5,
            height: 5,
            decoration: BoxDecoration(
              color: EsColors.BackGround,
              borderRadius: BorderRadius.circular(10),
            ),
          ),
          SizedBox(width: 10),
          Text('猜你喜欢',
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                  color: EsColors.TitleSecondary,
                  fontSize: EsSizes.LG,
                  fontWeight: EsFontWeights.Medium)),
          SizedBox(width: 10),
          Container(
            width: 5,
            height: 5,
            decoration: BoxDecoration(
              color: EsColors.BackGround,
              borderRadius: BorderRadius.circular(10),
            ),
          ),
          Expanded(child: YpLine()),
        ],
      ),
    );
  }

  /// 猜你喜欢
  /// 猜你喜欢
  Widget _guessLick() {
    return Padding(
      padding: EdgeInsets.only(
          left: 12,
          right: 12,
          top: 20,
          bottom: MediaQuery.of(context).padding.bottom + 10),
      child: Wrap(
        spacing: 10,
        runSpacing: 10,
        children: List.generate(
            state.TJlist.length,
            (index) => GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    print('点击猜你喜欢的商品详情');
                    if (state.TJlist[index]['style_store'] > 0) {
                      Get.toNamed(RouteConfig.goodsDetail, arguments: {
                        'itemNumId':
                            state.TJlist[index]['item_num_id'].toString(),
                        'styleNumId':
                            state.TJlist[index]['style_num_id'].toString(),
                        // 'shopId': SpUtil.getInt('storeShopNum').toString(),
                        'shopId':
                            SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
                        'ecStyleNumId':
                            state.TJlist[index]['ec_style_num_id'].toString(),
                        'typeIndex': state.TJlist[index]['is_pre_sale'] ?? 0,
                      });
                    }
                  },
                  child: Container(
                    decoration: EsDecoration.BoxShadowDefault,
                    width: MediaQuery.of(context).size.width / 2 - 18,
                    padding:
                        const EdgeInsets.only(left: 12, right: 12, bottom: 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Stack(
                          children: [
                            CachedImage(
                              path: state.TJlist[index]['image_default_id'],
                              width: MediaQuery.of(context).size.width / 2 - 24,
                              height:
                                  MediaQuery.of(context).size.width / 2 - 24,
                            ),
                            Positioned(
                              left: setWidth(97),
                              top: setWidth(106),
                              child: state.TJlist[index]['style_store'] <= 0
                                  ? Container(
                                      width: setWidth(120),
                                      height: setWidth(120),
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color:
                                            Color(0xffbbbbbb).withOpacity(0.7),
                                        borderRadius:
                                            BorderRadius.circular(setWidth(60)),
                                      ),
                                      child: Text(
                                        '售罄',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 15,
                                        ),
                                      ),
                                    )
                                  : SizedBox(),
                            ),
                          ],
                        ),
                        Text(state.TJlist[index]['title'],
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: EsColors.TitleSecondary,
                                fontSize: EsSizes.MD,
                                fontWeight: EsFontWeights.Normal)),
                        SizedBox(height: 16),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            RichText(
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              text: TextSpan(
                                  text: logic.getMoney(state.TJlist[index])[0],
                                  style: TextStyle(
                                      fontSize: EsSizes.LG,
                                      color: EsColors.Primary,
                                      fontWeight: EsFontWeights.Medium),
                                  children: <TextSpan>[
                                    TextSpan(
                                        text: logic
                                            .getMoney(state.TJlist[index])[1],
                                        style: TextStyle(
                                            decoration:
                                                TextDecoration.lineThrough,
                                            fontSize: EsSizes.XS,
                                            color: EsColors.ContentSecondary,
                                            fontWeight: EsFontWeights.Medium)),
                                  ]),
                            ),
                            GestureDetector(
                              onTap: () {
                                if (state.TJlist[index]['style_store'] > 0) {
                                  logic.bottomaddShoppingCart(
                                      ec_shop_num_id: state.TJlist[index]
                                              ['shop_num_id']
                                          .toString(),
                                      item_num_id: state.TJlist[index]
                                              ['default_item_num_id']
                                          .toString(),
                                      style_num_id: state.TJlist[index]
                                              ['style_num_id']
                                          .toString(),
                                      ec_style_num_id: state.TJlist[index]
                                              ['ec_style_num_id']
                                          .toString());
                                }
                              },
                              child: Image.asset(
                                'assets/images/shoppingCart_image.png',
                                width: setWidth(50),
                                color: state.TJlist[index]['style_store'] > 0
                                    ? Color(0xffEA5504)
                                    : Color(0xffcccccc),
                                height: setWidth(50),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                )),
      ),
    );
  }

  //自提点选择
  _selectProduct() {
    //用于在底部打开弹框的效果
    return SimpleDialog(
      title: Text(
        '选择自提点',
        style: TextStyle(
          color: Color(0xff333333),
          fontSize: 26.w,
          fontWeight: FontWeight.w100,
        ),
        textAlign: TextAlign.center,
      ),
      titleTextStyle: TextStyle(
          fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue),
      children: [
        Container(
          height: 400.w,
          child: Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(
                horizontal: 20.w,
              ),
              child: ListView.builder(
                shrinkWrap: true,
                itemBuilder: (ctx, i) {
                  return Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image(
                          image: AssetImage("assets/images/selectIcon1.png"),
                          width: 36.w,
                        ),
                        SizedBox(
                          width: 10.w,
                        ),
                        Expanded(
                          child: Text(
                            state.selfHelpAddressList[i]["sub_unit_name"],
                            style: TextStyle(
                              color: Color(0xff222222),
                              fontSize: 24.sp,
                            ),
                            maxLines: 2,
                            textAlign: TextAlign.start,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(top: 10.w, bottom: 10.w),
                          child: Divider(
                            color: Color(0xff000000),
                          ),
                        ),
                      ],
                    ),
                  );
                },
                itemCount: state.selfHelpAddressList.length,
              ),
            ),
          ),
        ),
        SimpleDialogOption(
          onPressed: () {},
          child: Container(
            color: Colors.white,
            child: Container(
              height: 80.w,
              decoration: BoxDecoration(
                color: Config.mainColor,
                borderRadius: BorderRadius.circular(40.w),
              ),
              child: GestureDetector(
                onTap: () {
                  // Get.toNamed(RouteConfig.productSelect);
                },
                child: Center(
                  child: Text(
                    "确定",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.w,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
      backgroundColor: Colors.white,
      elevation: 10,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(5),
      ),
    );
  }
}
